package ws

import "github.com/zeromicro/go-zero/core/logx"

// ChatRoomServer 聊天室可以有很多个
type ChatRoomServer struct {
	ChatRooms map[int64]*ChatRoom
	Clients   map[int64]*Client
}

func NewChatRoomServer() *ChatRoomServer {
	room := NewChatRoom()
	return &ChatRoomServer{
		// 暂时默认生成一个聊天室
		ChatRooms: map[int64]*ChatRoom{
			1: room,
		},
		Clients: map[int64]*Client{},
	}
}

func (crs *ChatRoomServer) Run() {
	for {
		select {
		case c := <-crs.ChatRooms[1].Register:
			crs.ChatRooms[1].Clients[c.UserId] = c
			crs.Clients[c.UserId] = c
			logx.Infof("%v,%v", c.UserId, "登录成功")
		case c := <-crs.ChatRooms[1].UnRegister:
			delete(crs.ChatRooms[1].Clients, c.UserId)
			delete(crs.Clients, c.UserId)
			c.Conn.Close()
			logx.Infof("%v,%v", c.UserId, "下线了。。。")
		case m := <-crs.ChatRooms[1].BroadcastData:
			for _, v := range crs.ChatRooms[1].Clients {
				v.Send <- m
			}
		}
	}
}
